from django.contrib.auth.decorators import login_required
from django.http import HttpResponse
from django.shortcuts import render, redirect, get_object_or_404
from django.contrib.auth import authenticate, login, logout
# Create your views here.
from accounts.forms import UserRegisterForm, UserLoginForm, UserAddressForm
from accounts.models import User, UserAddress
from utils import contants
from utils.verify import VerifyCode


def user_login(request):
    '''用户登录'''
    # 第一次访问url GET 展示表单 供用户输入
    # 第二次访问url POST 提交数据

    next_url = request.GET.get('next', 'index')

    if request.method == 'POST':
        form = UserLoginForm(request=request, data=request.POST)
        print(request.POST)
        client = VerifyCode(request)
        code = request.POST.get('vcode', None)
        rest = client.validate_code(code)
        print('验证结果', rest)
        # 表单是否通过了验证
        if form.is_valid():
            # 执行登录
            # print('验证通过')
            data = form.cleaned_data
            # # 查询用户信息
            # user = User.objects.get(username=data['username'], password=data['password'])
            # # 设置用户Id到session
            # request.session[contants.LOGIN_SESSION_ID] = user.id
            # # 登录成功后跳转到首页
            # return redirect('index')

            # 使用django-auth实现登录
            user = authenticate(request, username=data['username'], password=data['password'])
            if user is not None:
                login(request, user)
                request.session['user_id'] = user.id
                # 登录后的跳转

                return redirect(next_url)
        else:
            print(form.errors)
    else:
        form = UserLoginForm(request)

    return render(request, 'login.html', {
        'form': form,
        'next_url': next_url,
    })


def user_register(request):
    '''用户注册'''
    if request.method == 'POST':
        form = UserRegisterForm(request=request, data=request.POST)
        if form.is_valid():
            # 调用注册方法
            print('开始注册')
            form.register()
            print('注册成功')
            # return redirect('index')
            return HttpResponse('ok')
        else:
            print(form.errors)
    else:
        form = UserRegisterForm(request=request)
    return render(request, 'register.html', {
        'form': form,
    })


# 用户退出登录
def user_logout(request):
    logout(request)
    return redirect('index')

@login_required
def address_list(request):
    '''地址列表'''
    my_addr_list = UserAddress.objects.filter(user=request.user, is_valid=True)
    return render(request, 'address_list.html', {
        'my_addr_list': my_addr_list,
    })

@login_required
def address_edit(request, pk):
    # 地址的新增和编辑
    user = request.user
    addr = None
    initial = {}
    # 如果说pk为数字  则表示修改地址
    if pk.isdigit():
        # 查询地址相关信息
        addr = get_object_or_404(UserAddress, pk=pk, user=user, is_valid=True)
        initial['region'] = addr.get_regin_format()

    if request.method == 'POST':
        form = UserAddressForm(request=request, data=request.POST,
                               initial=initial, instance=addr)
        if form.is_valid():
            # 如果通过验证 将地址保存到数据库中
            form.save()
            return redirect('accounts:address_list')
    else:
        form = UserAddressForm(request=request, instance=addr, initial=initial)
    return render(request, 'address_edit.html', {
        'form': form
    })


def address_delete(request, pk):
    '''删除地址'''
    addr = get_object_or_404(UserAddress, pk=pk, is_valid=True, user=request.user)
    addr.is_valid = False
    addr.save()
    return HttpResponse('ok')